package net.oschina.arvin.sqlbuilder.definition;

import net.oschina.arvin.sqlbuilder.OrderItem;
import net.oschina.arvin.sqlbuilder.annotations.QueryCompare;
import net.oschina.arvin.sqlbuilder.enums.CompareType;
import net.oschina.arvin.sqlbuilder.utils.AssertUtil;
import net.oschina.arvin.sqlbuilder.utils.ReflectUtil;

import java.lang.reflect.Field;

/**
 * 直接字段查询
 *
 * @author Arvin
 * @time 2017/11/17 14:26
 */
public class DirectConditionColumnDefinition extends AbstractQueryConditionColumnDefinition {

    /**
     * 解析比较类型
     *
     * @param field              属性
     * @param defaultCompareType 默认查询类型
     * @return
     */
    private static CompareType parseCompareType(Field field, CompareType defaultCompareType) {
        AssertUtil.assertNotNull(field, "要计算比较类型的属性不能为空！");
        defaultCompareType = null == defaultCompareType ? CompareType.EQUAL : defaultCompareType;

        QueryCompare queryCompareAnnotation = ReflectUtil.getFieldAnnotation(field, QueryCompare.class);
        if (null == queryCompareAnnotation || null == queryCompareAnnotation.value()) {
            return defaultCompareType;
        }
        return queryCompareAnnotation.value();
    }

    /** 查询条件字段 */
    private final Field field;

    public DirectConditionColumnDefinition(Field field, QueryConditionDefinition queryConditionDefinition) {
        super(field.getName(), parseCompareType(field, CompareType.EQUAL), queryConditionDefinition);

        this.field = field;
    }

    public Field getField() {
        return field;
    }

    public Class<?> getFieldType() {
        return this.field.getType();
    }

    @Override
    protected OrderItem customCreateOrderItem(Class<?> modelType) {

        return createOrderItemByField(modelType, this.field);
    }

    @Override
    protected ConditionItem customCreateConditionItem(ColumnDefinition modelColumnDefinition) {
        return new DirectConditionItem(modelColumnDefinition, this);
    }
}
